#import "MO2XMLEntitiesExporter.h"
#import "MO2XMLEntityExporter.h"

@implementation MO2XMLEntitiesExporter

- (id)initWithEntityNames:(NSArray *)names {
	self = [super init];
	if(self) {
		[self setManagedObjectContext:nil];
		[self setEntityNames:names];
	}
	return self;
}

- (void)dealloc {
	[managedObjectContext release];
	[entityNames release];
	
	[super dealloc];
}

- (NSArray *)entityNames {
	return entityNames;
}

- (void)setEntityNames:(NSArray *)value {
	[value retain];
	[entityNames release];
	entityNames = value;
}

- (NSArray *)entitiesAsDictionaries {
	NSMutableArray *entitiesAsDictionariesReturn = [[NSMutableArray alloc] init];
	
	NSArray *entities = [self entityNames];
	NSEnumerator *entitiesEnumerator = [entities objectEnumerator];
	id entity;
	while(entity = [entitiesEnumerator nextObject]) {
		MO2XMLEntityExporter *entityExporter = [[MO2XMLEntityExporter alloc] initWithEntityName:entity];
		[entityExporter setManagedObjectContext:[self managedObjectContext]];
		
		NSMutableDictionary *entityDict = [[NSMutableDictionary alloc] init];
		[entityDict setObject:[entityExporter managedObjectsAsDictionaries] forKey:@"data"];
		[entityDict setObject:entity forKey:@"name"];
		
		[entitiesAsDictionariesReturn addObject:entityDict];
		
		[entityDict release];
		[entityExporter release];
	}
	
	return entitiesAsDictionariesReturn;
}	

- (BOOL)writeToFile:(NSString *)aPath atomically:(BOOL)flag {
	return [[self  entitiesAsDictionaries] writeToFile:aPath atomically:flag];
}

@end
